<?php

namespace backend\controllers;

use common\cache\ConfigCache;
use common\helpers\commonApi;
use common\helpers\RedisApi;
use common\models\Config;
use common\services\ConfigService;
use Yii;

/**
 * 参数配置控制器
 * Class ConfigController
 * @package backend\controllers
 */
class ConfigController extends BaseController
{
    public $uploadWay = [
        'local' => '本地',
        'qiniu' => '七牛云',
        'aly' => '阿里云',
        'txy' => '腾讯云',
    ];

    public function init()
    {
        parent::init();
        $this->model = Config::class;
        if (Yii::$app->request->isGet && !Yii::$app->request->isAjax) {
            Yii::$app->view->params['styleList'] = ConfigService::styleList();
            Yii::$app->view->params['groupList'] = ConfigService::getConfig('sys_config_group');
        }
    }

    public function actionSite()
    {
        if (Yii::$app->request->isPost) {
            $input = Yii::$app->request->post();
            if (empty($input)) return commonApi::message('无更新数据', false);
            $redis = [];
            foreach ($input as $id => $value) {
                if ($id) {
                    $info = Config::findOne($id);
                    if ($info) {
                        if ($info->type=='redis_hostname'){
                            $redis['hostname'] = $value;
                        }
                        if ($info->type=='redis_port'){
                            $redis['port'] = $value;
                        }
                        if ($info->type=='redis_password'){
                            $redis['password'] = $value;
                        }
                        $info->value = $value;
                        $info->save(false);
                    }
                }
            }
            (new RedisApi(''))->config($redis);
            return commonApi::message('保存成功', true);
        }
        $lists = ConfigService::getListByGroup();
        return $this->render('', ['lists' => $lists]);
    }

    public function actionDelcache()
    {
        ConfigCache::clear();
        return commonApi::message();
    }

    /**
     * 上传设置
     * @return array|string
     */
    public function actionUploadSet()
    {
        if (Yii::$app->request->isPost) {
            $post = Yii::$app->request->post();
            Yii::$app->cache->set('upload_info',json_encode($post));
            return commonApi::message('设置成功', true);
        }
        $info = Yii::$app->cache->get('upload_info');
        $info = $info?json_decode($info,true):[];
        $info['current_way'] = $info['current_way'] ?? 'local';//保存方式
        $info['qiniu'] = $info['qiniu'] ?? [];//七牛云
        return $this->render('', ['info' => $info, 'uploadWay' => $this->uploadWay]);
    }
}
